#include"database.h"
#include"stack.h"

int touch_command(MYSQL* conn, const char* name, DirStack* stack, const char* hash, const char* user_name) {
    int p_id;
    if (get_top(stack, &p_id) != 0) {
        fprintf(stderr, "当前路径栈为空，无法获取父目录ID\n");
        return -1;
    }

    MYSQL_STMT* stmt = mysql_stmt_init(conn);
    if (!stmt) {
        fprintf(stderr, "mysql_stmt_init failed\n");
        return -1;
    }

    const char* sql = "INSERT INTO nodes (name, user_name, p_id, hash, is_dir) VALUES (?, ?, ?, ?, 0)";
    if (mysql_stmt_prepare(stmt, sql, strlen(sql)) != 0) {
        fprintf(stderr, "mysql_stmt_prepare failed: %s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return -1;
    }

    MYSQL_BIND bind[4];
    memset(bind, 0, sizeof(bind));

    // name
    bind[0].buffer_type = MYSQL_TYPE_STRING;
    bind[0].buffer = (void*)name;
    bind[0].buffer_length = strlen(name);

    // user_name
    bind[1].buffer_type = MYSQL_TYPE_STRING;
    bind[1].buffer = (void*)user_name;
    bind[1].buffer_length = strlen(user_name);

    // p_id
    bind[2].buffer_type = MYSQL_TYPE_LONG;
    bind[2].buffer = (void*)&p_id;

    // hash
    bind[3].buffer_type = MYSQL_TYPE_STRING;
    bind[3].buffer = (void*)hash;
    bind[3].buffer_length = strlen(hash);

    if (mysql_stmt_bind_param(stmt, bind) != 0) {
        fprintf(stderr, "mysql_stmt_bind_param failed: %s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return -1;
    }

    if (mysql_stmt_execute(stmt) != 0) {
        fprintf(stderr, "mysql_stmt_execute failed: %s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return -1;
    }

    mysql_stmt_close(stmt);
    return 0;
}

